Addresses review comments
authorjluner <justin.j.luner@gmail.com>
Thu, 25 May 2017 04:45:14 +0000 (23:45 -0500)
committerjluner <justin.j.luner@gmail.com>
Thu, 25 May 2017 04:45:14 +0000 (23:45 -0500)
* rebased
* removed `human` (deferring removing `internal` to a later PR)
* cargo_test.rs - fails on other error kinds
* unnecessary `map_err(CargoError::from)` removed
* fold NetworkError entirely into CargoError
* added justification comment for `extend_lifetime`
* various formatting goofs

The following tests are currently failing:
* `http_auth_offered`
* `custom_build_script_failed`
* `build_deps_for_the_right_arch`
* `dep_with_bad_submodule`
* `update_with_shared_deps`
* `finds_author_email`
* `finds_author_user`
* `finds_author_user_escaped`
* `finds_author_username`
* `finds_git_author`
* `exit_code`

49 files changed:
src/bin/bench.rs
src/bin/cargo.rs
src/bin/help.rs
src/bin/locate_project.rs
src/bin/login.rs
src/bin/rustc.rs
src/bin/test.rs
src/cargo/core/dependency.rs
src/cargo/core/package.rs
src/cargo/core/package_id_spec.rs
src/cargo/core/registry.rs
src/cargo/core/resolver/mod.rs
src/cargo/core/source.rs
src/cargo/core/workspace.rs
src/cargo/lib.rs
src/cargo/ops/cargo_clean.rs
src/cargo/ops/cargo_install.rs
src/cargo/ops/cargo_new.rs
src/cargo/ops/cargo_package.rs
src/cargo/ops/cargo_read_manifest.rs
src/cargo/ops/cargo_run.rs
src/cargo/ops/cargo_rustc/context.rs
src/cargo/ops/cargo_rustc/fingerprint.rs
src/cargo/ops/cargo_rustc/job_queue.rs
src/cargo/ops/cargo_rustc/layout.rs
src/cargo/ops/cargo_rustc/mod.rs
src/cargo/ops/cargo_test.rs
src/cargo/ops/lockfile.rs
src/cargo/ops/registry.rs
src/cargo/ops/resolve.rs
src/cargo/sources/config.rs
src/cargo/sources/directory.rs
src/cargo/sources/git/utils.rs
src/cargo/sources/path.rs
src/cargo/sources/registry/index.rs
src/cargo/sources/registry/local.rs
src/cargo/sources/registry/remote.rs
src/cargo/sources/replaced.rs
src/cargo/util/cfg.rs
src/cargo/util/config.rs
src/cargo/util/errors.rs
src/cargo/util/flock.rs
src/cargo/util/important_paths.rs
src/cargo/util/mod.rs
src/cargo/util/network.rs
src/cargo/util/paths.rs
src/cargo/util/to_url.rs
src/cargo/util/toml.rs
tests/doc.rs

index 6b2b8166638baadb2bccf0a038f5717be2990f24..445d5d68bb13ed8a9725b764998e862c5bcfab30 100644 (file)
@@ -1,6 +1,6 @@
 use cargo::core::Workspace;
 use cargo::ops::{self, MessageFormat, Packages};
-use cargo::util::{CliResult, CliError, Config, human, CargoErrorKind};
+use cargo::util::{CliResult, CliError, Config, CargoErrorKind};
 use cargo::util::important_paths::{find_root_manifest_for_wd};
 
 #[derive(RustcDecodable)]
@@ -128,7 +128,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult {
         None => Ok(()),
         Some(err) => {
             Err(match err.exit.as_ref().and_then(|e| e.code()) {
-                Some(i) => CliError::new(human("bench failed"), i),
+                Some(i) => CliError::new("bench failed".into(), i),
                 None => CliError::new(CargoErrorKind::CargoTestErrorKind(err).into(), 101)
             })
         }
index 73f7f81953f19ffbaa6948ab321e202720381473..4c838a632907453c75c695e06422d386145f2f99 100644 (file)
@@ -17,7 +17,7 @@ use std::fs;
 use std::path::{Path, PathBuf};
 
 use cargo::core::shell::{Verbosity, ColorConfig};
-use cargo::util::{self, CliResult, lev_distance, Config, human, CargoResult, CargoError, CargoErrorKind};
+use cargo::util::{self, CliResult, lev_distance, Config, CargoResult, CargoError, CargoErrorKind};
 use cargo::util::CliError;
 
 #[derive(RustcDecodable)]
@@ -84,7 +84,7 @@ fn main() {
     let result = (|| {
         let args: Vec<_> = try!(env::args_os()
             .map(|s| {
-                s.into_string().map_err(|s| human(format!("invalid unicode in argument: {:?}", s)))
+                s.into_string().map_err(|s| CargoError::from(format!("invalid unicode in argument: {:?}", s)))
             })
             .collect());
         let rest = &args;
@@ -180,7 +180,7 @@ fn execute(flags: Flags, config: &Config) -> CliResult {
 
     if let Some(ref code) = flags.flag_explain {
         let mut procss = config.rustc()?.process();
-        procss.arg("--explain").arg(code).exec().map_err(human)?;
+        procss.arg("--explain").arg(code).exec()?;
         return Ok(());
     }
 
@@ -309,7 +309,7 @@ fn execute_external_subcommand(config: &Config, cmd: &str, args: &[String]) -> C
     let command = match path {
         Some(command) => command,
         None => {
-            return Err(human(match find_closest(config, cmd) {
+            return Err(CargoError::from(match find_closest(config, cmd) {
                     Some(closest) => {
                         format!("no such subcommand: `{}`\n\n\tDid you mean `{}`?\n",
                                 cmd,
index a068b0a2c63bddf660d7e62fc1ae09bd60168963..f59e24f3ebd8c7902e774d69538bbbf07f493771 100644 (file)
@@ -1,4 +1,4 @@
-use cargo::util::{CliResult, CliError, Config, human};
+use cargo::util::{CliResult, CliError, Config};
 
 #[derive(RustcDecodable)]
 pub struct Options;
@@ -18,5 +18,5 @@ pub fn execute(_: Options, _: &Config) -> CliResult {
     // This is a dummy command just so that `cargo help help` works.
     // The actual delegation of help flag to subcommands is handled by the
     // cargo command.
-    Err(CliError::new(human("help command should not be executed directly"), 101))
+    Err(CliError::new("help command should not be executed directly".into(), 101))
 }
index a7d83b4be8d6a074e0e9c657279667dad7ca7d9e..7c7727aa221837f03b4f873523d675f59ce43a16 100644 (file)
@@ -1,5 +1,5 @@
 use cargo;
-use cargo::util::{CliResult, CliError, human, Config};
+use cargo::util::{CliResult, CliError, Config};
 use cargo::util::important_paths::{find_root_manifest_for_wd};
 
 #[derive(RustcDecodable)]
@@ -28,9 +28,9 @@ pub fn execute(flags: LocateProjectFlags,
     let root = find_root_manifest_for_wd(flags.flag_manifest_path, config.cwd())?;
 
     let string = root.to_str()
-                      .ok_or_else(|| human("Your project path contains \
+                      .ok_or_else(|| "Your project path contains \
                                              characters not representable in \
-                                             Unicode"))
+                                             Unicode".into())
                       .map_err(|e| CliError::new(e, 1))?;
 
     let location = ProjectLocation { root: string.to_string() };
index 75a8fd7f848e0e42d4b71158aa127861434d0053..6e7841717b69c53d5ee1cc08d8b45df48148f663 100644 (file)
@@ -4,7 +4,7 @@ use std::io;
 use cargo::ops;
 use cargo::core::{SourceId, Source};
 use cargo::sources::RegistrySource;
-use cargo::util::{CliResult, CargoResultExt, Config, human};
+use cargo::util::{CliResult, CargoResultExt, Config};
 
 #[derive(RustcDecodable)]
 pub struct Options {
@@ -52,7 +52,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult {
             let mut line = String::new();
             let input = io::stdin();
             input.lock().read_line(&mut line).chain_err(|| {
-                human("failed to read stdin")
+                "failed to read stdin"
             })?;
             line
         }
index 8805c8f8a4ec14f6281d94710ed29cee78604148..3ee18a8623438b53b8eb41762c1f196f9b5e3d7e 100644 (file)
@@ -3,7 +3,7 @@ use std::env;
 use cargo::core::Workspace;
 use cargo::ops::{self, CompileOptions, CompileMode, MessageFormat, Packages};
 use cargo::util::important_paths::{find_root_manifest_for_wd};
-use cargo::util::{CliResult, CliError, Config, human};
+use cargo::util::{CliResult, CliError, Config};
 
 #[derive(RustcDecodable)]
 pub struct Options {
@@ -98,8 +98,8 @@ pub fn execute(options: Options, config: &Config) -> CliResult {
         Some("bench") => CompileMode::Bench,
         Some("check") => CompileMode::Check,
         Some(mode) => {
-            let err = human(format!("unknown profile: `{}`, use dev,
-                                     test, or bench", mode));
+            let err = format!("unknown profile: `{}`, use dev,
+                                     test, or bench", mode).into();
             return Err(CliError::new(err, 101))
         }
     };
index 22e278043dbd397f05f808f225011b2b7234ac6f..a92d5d62f1a5fa041d8648f5e97100006a1cc070 100644 (file)
@@ -1,6 +1,6 @@
 use cargo::core::Workspace;
 use cargo::ops::{self, MessageFormat, Packages};
-use cargo::util::{CliResult, CliError, human, Config, CargoErrorKind};
+use cargo::util::{CliResult, CliError, Config, CargoErrorKind};
 use cargo::util::important_paths::find_root_manifest_for_wd;
 
 #[derive(RustcDecodable)]
@@ -163,7 +163,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult {
         None => Ok(()),
         Some(err) => {
             Err(match err.exit.as_ref().and_then(|e| e.code()) {
-                Some(i) => CliError::new(human(err.hint()), i),
+                Some(i) => CliError::new(err.hint().into(), i),
                 None => CliError::new(CargoErrorKind::CargoTestErrorKind(err).into(), 101),
             })
         }
index ff8d3976c4d808cf1552b2c49c2fbdb56d6d97c1..3b75934ebb5f14e2a23b628c378400e63a2a373c 100644 (file)
@@ -7,7 +7,7 @@ use semver::ReqParseError;
 use serde::ser;
 
 use core::{SourceId, Summary, PackageId};
-use util::{Cfg, CfgExpr, human, Config};
+use util::{Cfg, CfgExpr, Config};
 use util::errors::{CargoResult, CargoResultExt, CargoError};
 
 /// Information about a dependency requested by a Cargo manifest.
@@ -368,7 +368,7 @@ impl FromStr for Platform {
         if s.starts_with("cfg(") && s.ends_with(")") {
             let s = &s[4..s.len()-1];
             s.parse().map(Platform::Cfg).chain_err(|| {
-                human(format!("failed to parse `{}` as a cfg expression", s))
+                format!("failed to parse `{}` as a cfg expression", s)
             })
         } else {
             Ok(Platform::Name(s.to_string()))
index 00cbd222d369f891cfbf757f82200da90fffd7cc..bdb7f41d4c3a9cf3a0e1579f63ec5a3ebec9b621 100644 (file)
@@ -11,7 +11,7 @@ use toml;
 use core::{Dependency, Manifest, PackageId, SourceId, Target};
 use core::{Summary, SourceMap};
 use ops;
-use util::{Config, LazyCell, internal, human, lev_distance};
+use util::{Config, LazyCell, internal, lev_distance};
 use util::errors::{CargoResult, CargoResultExt};
 
 /// Information about a package that is available somewhere in the file system.
@@ -194,7 +194,7 @@ impl<'cfg> PackageSet<'cfg> {
             internal(format!("couldn't find source for `{}`", id))
         })?;
         let pkg = source.download(id).chain_err(|| {
-            human("unable to get packages from source")
+            "unable to get packages from source"
         })?;
         assert!(slot.fill(pkg).is_ok());
         Ok(slot.borrow().unwrap())
index ad56601386dd68a56c577e1ded309b77f7f2726d..c24b48a365d00ca4f634228954ce6c6609684c26 100644 (file)
@@ -5,8 +5,8 @@ use semver::Version;
 use url::Url;
 
 use core::PackageId;
-use util::{ToUrl, human, ToSemver};
-use util::errors::{CargoResult, CargoResultExt};
+use util::{ToUrl, ToSemver};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 
 #[derive(Clone, PartialEq, Eq, Debug)]
 pub struct PackageIdSpec {
@@ -30,7 +30,7 @@ impl PackageIdSpec {
         let mut parts = spec.splitn(2, ':');
         let name = parts.next().unwrap();
         let version = match parts.next() {
-            Some(version) => Some(Version::parse(version).map_err(human)?),
+            Some(version) => Some(Version::parse(version)?),
             None => None,
         };
         for ch in name.chars() {
@@ -49,7 +49,7 @@ impl PackageIdSpec {
         where I: IntoIterator<Item=&'a PackageId>
     {
         let spec = PackageIdSpec::parse(spec).chain_err(|| {
-            human(format!("invalid package id specification: `{}`", spec))
+            format!("invalid package id specification: `{}`", spec)
         })?;
         spec.query(i)
     }
@@ -70,11 +70,11 @@ impl PackageIdSpec {
         url.set_fragment(None);
         let (name, version) = {
             let mut path = url.path_segments().ok_or_else(|| {
-                human(format!("pkgid urls must have a path: {}", url))
+                CargoError::from(format!("pkgid urls must have a path: {}", url))
             })?;
             let path_name = path.next_back().ok_or_else(|| {
-                human(format!("pkgid urls must have at least one path \
-                               component: {}", url))
+                CargoError::from(format!("pkgid urls must have at least one path \
+                                          component: {}", url))
             })?;
             match frag {
                 Some(fragment) => {
@@ -82,7 +82,7 @@ impl PackageIdSpec {
                     let name_or_version = parts.next().unwrap();
                     match parts.next() {
                         Some(part) => {
-                            let version = part.to_semver().map_err(human)?;
+                            let version = part.to_semver()?;
                             (name_or_version.to_string(), Some(version))
                         }
                         None => {
@@ -90,8 +90,7 @@ impl PackageIdSpec {
                                               .is_alphabetic() {
                                 (name_or_version.to_string(), None)
                             } else {
-                                let version = name_or_version.to_semver()
-                                                                  .map_err(human)?;
+                                let version = name_or_version.to_semver()?;
                                 (path_name.to_string(), Some(version))
                             }
                         }
@@ -150,7 +149,7 @@ impl PackageIdSpec {
                 let mut vec = vec![ret, other];
                 vec.extend(ids);
                 minimize(&mut msg, vec, self);
-                Err(human(msg))
+                Err(msg.into())
             }
             None => Ok(ret)
         };
index 0929aa9010497d432ae851f4d0af6af03bc4705e..04042b442e26f23e361a96fd9eaef43d7927c171 100644 (file)
@@ -2,7 +2,7 @@ use std::collections::HashMap;
 
 use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package};
 use core::PackageSet;
-use util::{Config, human, profile};
+use util::{Config, profile};
 use util::errors::{CargoResult, CargoResultExt};
 use sources::config::SourceConfigMap;
 
@@ -190,7 +190,7 @@ impl<'cfg> PackageRegistry<'cfg> {
             // Ensure the source has fetched all necessary remote data.
             let _p = profile::start(format!("updating: {}", source_id));
             self.sources.get_mut(source_id).unwrap().update()
-        })().chain_err(|| human(format!("Unable to update {}", source_id)))
+        })().chain_err(|| format!("Unable to update {}", source_id))
     }
 
     fn query_overrides(&mut self, dep: &Dependency)
@@ -338,8 +338,8 @@ impl<'cfg> Registry for PackageRegistry<'cfg> {
     fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
         // Ensure the requested source_id is loaded
         self.ensure_loaded(dep.source_id(), Kind::Normal).chain_err(|| {
-            human(format!("failed to load source for a dependency \
-                           on `{}`", dep.name()))
+            format!("failed to load source for a dependency \
+                     on `{}`", dep.name())
         })?;
 
         let override_summary = self.query_overrides(&dep)?;
index f47f5d8e0e3c66d45005e593216482778406e829..987fac1e48fdb2a9c3194508a4324e730916c536 100644 (file)
@@ -56,7 +56,7 @@ use semver;
 
 use core::{PackageId, Registry, SourceId, Summary, Dependency};
 use core::PackageIdSpec;
-use util::{Graph, human};
+use util::Graph;
 use util::errors::{CargoResult, CargoError};
 use util::profile;
 use util::graph::{Nodes, Edges};
@@ -633,7 +633,7 @@ fn activation_error(cx: &Context,
                                         .collect::<Vec<_>>()
                                         .join(", ")));
 
-        return human(msg)
+        return msg.into()
     }
 
     // Once we're all the way down here, we're definitely lost in the
@@ -696,7 +696,7 @@ fn activation_error(cx: &Context,
                 dep.version_req())
     };
 
-    human(msg)
+    msg.into()
 }
 
 // Returns if `a` and `b` are compatible in the semver sense. This is a
@@ -888,10 +888,10 @@ impl<'a> Context<'a> {
 
             let mut summaries = registry.query(dep)?.into_iter();
             let s = summaries.next().ok_or_else(|| {
-                human(format!("no matching package for override `{}` found\n\
-                               location searched: {}\n\
-                               version required: {}",
-                              spec, dep.source_id(), dep.version_req()))
+                format!("no matching package for override `{}` found\n\
+                         location searched: {}\n\
+                         version required: {}",
+                         spec, dep.source_id(), dep.version_req())
             })?;
             let summaries = summaries.collect::<Vec<_>>();
             if summaries.len() > 0 {
index 75f83710c7de1825e2a0d558830e5e04cfd26a63..9f32d692dfed261477ceed5660f25790f39a8915 100644 (file)
@@ -16,7 +16,7 @@ use ops;
 use sources::git;
 use sources::{PathSource, GitSource, RegistrySource, CRATES_IO};
 use sources::DirectorySource;
-use util::{human, Config, CargoResult, ToUrl};
+use util::{Config, CargoResult, ToUrl};
 
 /// A Source finds and downloads remote packages based on names and
 /// versions.
@@ -138,7 +138,7 @@ impl SourceId {
     pub fn from_url(string: &str) -> CargoResult<SourceId> {
         let mut parts = string.splitn(2, '+');
         let kind = parts.next().unwrap();
-        let url = parts.next().ok_or(human(format!("invalid source `{}`", string)))?;
+        let url = parts.next().ok_or_else(|| format!("invalid source `{}`", string))?;
 
         match kind {
             "git" => {
@@ -169,7 +169,7 @@ impl SourceId {
                 let url = url.to_url()?;
                 Ok(SourceId::new(Kind::Path, url))
             }
-            kind => Err(human(format!("unsupported source protocol: {}", kind)))
+            kind => Err(format!("unsupported source protocol: {}", kind).into())
         }
     }
 
index cae6bc04a90f7b83abac05d1c343a72eacbfaf23..36df965eb2f9a0b58fc21ec16bfce0d472fd8d3b 100644 (file)
@@ -8,7 +8,7 @@ use glob::glob;
 use core::{Package, VirtualManifest, EitherManifest, SourceId};
 use core::{PackageIdSpec, Dependency, Profile, Profiles};
 use ops;
-use util::{Config, Filesystem, human};
+use util::{Config, Filesystem};
 use util::errors::{CargoResult, CargoResultExt};
 use util::paths;
 
@@ -165,9 +165,9 @@ impl<'cfg> Workspace<'cfg> {
     /// indicating that something else should be passed.
     pub fn current(&self) -> CargoResult<&Package> {
         self.current_opt().ok_or_else(||
-            human(format!("manifest path `{}` is a virtual manifest, but this \
-                           command requires running against an actual package in \
-                           this workspace", self.current_manifest.display()))
+            format!("manifest path `{}` is a virtual manifest, but this \
+                     command requires running against an actual package in \
+                     this workspace", self.current_manifest.display()).into()
         )
     }
 
@@ -553,11 +553,11 @@ fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
         None => return Ok(Vec::new()),
     };
     let res = glob(path).chain_err(|| {
-        human(format!("could not parse pattern `{}`", &path))
+        format!("could not parse pattern `{}`", &path)
     })?;
     res.map(|p| {
         p.chain_err(|| {
-            human(format!("unable to match path to pattern `{}`", &path))
+            format!("unable to match path to pattern `{}`", &path)
         })
     }).collect()
 }
index 70bf603f265fe7a58f2557531be1f26add9f21fa..06eb8705af454f4de872f99aec0baef4fd52bd7a 100755 (executable)
@@ -42,13 +42,13 @@ use core::{Shell, MultiShell, ShellConfig, Verbosity, ColorConfig};
 use core::shell::Verbosity::{Verbose};
 use term::color::{BLACK};
 
-pub use util::{CargoError, CargoErrorKind, CargoResult, CliError, CliResult, human, Config};
+pub use util::{CargoError, CargoErrorKind, CargoResult, CliError, CliResult, Config};
 
 pub const CARGO_ENV: &'static str = "CARGO";
 
 macro_rules! bail {
     ($($fmt:tt)*) => (
-        return Err(::util::human(&format_args!($($fmt)*)))
+        return Err(::util::errors::CargoError::from(format_args!($($fmt)*).to_string()))
     )
 }
 
@@ -116,7 +116,7 @@ pub fn call_main_without_stdin<Flags: Decodable>(
 
     let flags = docopt.decode().map_err(|e| {
         let code = if e.fatal() {1} else {0};
-        CliError::new(human(e.to_string()), code)
+        CliError::new(e.to_string().into(), code)
     })?;
 
     exec(flags, config)
@@ -212,8 +212,16 @@ fn handle_cause<E, EKind>(cargo_err: E, shell: &mut MultiShell) -> bool where E:
         let _ = shell.err().say(format!("  {}", error), BLACK);
     }
 
-    unsafe fn extend_lifetime(r: &Error) -> &'static Error {
-        std::mem::transmute::<&Error, &'static Error>(r)    
+    //Error inspection in non-verbose mode requires inspecting the
+    //error kind to avoid printing Internal errors. The downcasting
+    //machinery requires &(Error + 'static), but the iterator (and
+    //underlying `cause`) return &Error. Because the borrows are
+    //constrained to this handling method, and because the original
+    //error object is constrained to be 'static, we're casting away
+    //the borrow's actual lifetime for purposes of downcasting and
+    //inspecting the error chain
+    unsafe fn extend_lifetime(r: &Error) -> &(Error + 'static) {
+        std::mem::transmute::<&Error, &Error>(r)    
     }
 
     let verbose = shell.get_verbose();
@@ -224,8 +232,7 @@ fn handle_cause<E, EKind>(cargo_err: E, shell: &mut MultiShell) -> bool where E:
         for err in cargo_err.iter().skip(1) {
             print(err.to_string(), shell);
         }
-    }
-    else {
+    } else {
         //The first error has already been printed to the shell
         //Print remaining errors until one marked as Internal appears
         for err in cargo_err.iter().skip(1) {
index 5d7af68527d6f1c5f38eed085fdd7d9a384b8fcc..c7f1b28f8b6f512ea39ab986737e2550eab7440c 100644 (file)
@@ -3,7 +3,7 @@ use std::fs;
 use std::path::Path;
 
 use core::{Profiles, Workspace};
-use util::{human, Config};
+use util::Config;
 use util::errors::{CargoResult, CargoResultExt};
 use ops::{self, Context, BuildConfig, Kind, Unit};
 
@@ -97,11 +97,11 @@ fn rm_rf(path: &Path) -> CargoResult<()> {
     let m = fs::metadata(path);
     if m.as_ref().map(|s| s.is_dir()).unwrap_or(false) {
         fs::remove_dir_all(path).chain_err(|| {
-            human("could not remove build directory")
+            "could not remove build directory"
         })?;
     } else if m.is_ok() {
         fs::remove_file(path).chain_err(|| {
-            human("failed to remove build artifact")
+            "failed to remove build artifact"
         })?;
     }
     Ok(())
index bc77ddc961dea5e37ace811f0f3e39a66c733032..ba1829accbd79a971d9991a60e0b20be68d97319 100644 (file)
@@ -16,9 +16,9 @@ use core::{SourceId, Source, Package, Dependency, PackageIdSpec};
 use core::{PackageId, Workspace};
 use ops::{self, CompileFilter, DefaultExecutor};
 use sources::{GitSource, PathSource, SourceConfigMap};
-use util::{Config, human, internal};
+use util::{Config, internal};
 use util::{Filesystem, FileLock};
-use util::errors::{CargoResult, CargoResultExt};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 
 #[derive(Deserialize, Serialize)]
 #[serde(untagged)]
@@ -71,18 +71,18 @@ pub fn install(root: Option<&str>,
                             .expect("path sources must have a valid path");
         let mut src = PathSource::new(&path, source_id, config);
         src.update().chain_err(|| {
-            human(format!("`{}` is not a crate root; specify a crate to \
-                           install from crates.io, or use --path or --git to \
-                           specify an alternate source", path.display()))
+            format!("`{}` is not a crate root; specify a crate to \
+                     install from crates.io, or use --path or --git to \
+                     specify an alternate source", path.display())
         })?;
         select_pkg(PathSource::new(&path, source_id, config),
                    krate, vers, config, &mut |path| path.read_packages())?
     } else {
         select_pkg(map.load(source_id)?,
                    krate, vers, config,
-                   &mut |_| Err(human("must specify a crate to install from \
-                                       crates.io, or use --path or --git to \
-                                       specify alternate source")))?
+                   &mut |_| Err("must specify a crate to install from \
+                                 crates.io, or use --path or --git to \
+                                 specify alternate source".into()))?
     };
 
 
@@ -124,8 +124,8 @@ pub fn install(root: Option<&str>,
             td.into_path();
         }
 
-        human(format!("failed to compile `{}`, intermediate artifacts can be \
-                       found at `{}`", pkg, ws.target_dir().display()))
+        CargoError::from(format!("failed to compile `{}`, intermediate artifacts can be \
+                                  found at `{}`", pkg, ws.target_dir().display()))
     })?;
     let binaries: Vec<(&str, &Path)> = compile.binaries.iter().map(|bin| {
         let name = bin.file_name().unwrap();
@@ -161,8 +161,8 @@ pub fn install(root: Option<&str>,
             }
         }
         fs::copy(src, &dst).chain_err(|| {
-            human(format!("failed to copy `{}` to `{}`", src.display(),
-                          dst.display()))
+            format!("failed to copy `{}` to `{}`", src.display(),
+                    dst.display())
         })?;
     }
 
@@ -178,8 +178,8 @@ pub fn install(root: Option<&str>,
         let dst = dst.join(bin);
         config.shell().status("Installing", dst.display())?;
         fs::rename(&src, &dst).chain_err(|| {
-            human(format!("failed to move `{}` to `{}`", src.display(),
-                          dst.display()))
+            format!("failed to move `{}` to `{}`", src.display(),
+                    dst.display())
         })?;
         installed.bins.push(dst);
     }
@@ -194,8 +194,8 @@ pub fn install(root: Option<&str>,
                 let dst = dst.join(bin);
                 config.shell().status("Replacing", dst.display())?;
                 fs::rename(&src, &dst).chain_err(|| {
-                    human(format!("failed to move `{}` to `{}`", src.display(),
-                                  dst.display()))
+                    format!("failed to move `{}` to `{}`", src.display(),
+                            dst.display())
                 })?;
                 replaced_names.push(bin);
             }
@@ -304,8 +304,8 @@ fn select_pkg<'a, T>(mut source: T,
                 None => {
                     let vers_info = vers.map(|v| format!(" with version `{}`", v))
                                         .unwrap_or(String::new());
-                    Err(human(format!("could not find `{}` in `{}`{}", name,
-                                      source.source_id(), vers_info)))
+                    Err(format!("could not find `{}` in `{}`{}", name,
+                                source.source_id(), vers_info).into())
                 }
             }
         }
@@ -347,7 +347,7 @@ fn one<I, F>(mut i: I, f: F) -> CargoResult<Option<I::Item>>
         (Some(i1), Some(i2)) => {
             let mut v = vec![i1, i2];
             v.extend(i);
-            Err(human(f(v)))
+            Err(f(v).into())
         }
         (Some(i), None) => Ok(Some(i)),
         (None, _) => Ok(None)
@@ -382,7 +382,7 @@ fn check_overwrites(dst: &Path,
         }
     }
     msg.push_str("Add --force to overwrite");
-    Err(human(msg))
+    Err(msg.into())
 }
 
 fn find_duplicates(dst: &Path,
@@ -440,7 +440,7 @@ fn read_crate_list(mut file: &File) -> CargoResult<CrateListingV1> {
             }
         }
     })().chain_err(|| {
-        human("failed to parse crate metadata")
+        "failed to parse crate metadata"
     })
 }
 
@@ -452,7 +452,7 @@ fn write_crate_list(mut file: &File, listing: CrateListingV1) -> CargoResult<()>
         file.write_all(data.as_bytes())?;
         Ok(())
     })().chain_err(|| {
-        human("failed to write crate metadata")
+        "failed to write crate metadata"
     })
 }
 
index 0f63694a9c641309f35331f3e669a37c9ffde4c8..40597a6bbf21ec05efe49e7a9871ba0f415be3e4 100644 (file)
@@ -11,9 +11,9 @@ use term::color::BLACK;
 
 use core::Workspace;
 use ops::is_bad_artifact_name;
-use util::{GitRepo, HgRepo, PijulRepo, human, internal};
+use util::{GitRepo, HgRepo, PijulRepo, internal};
 use util::{Config, paths};
-use util::errors::{CargoResult, CargoResultExt};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 
 use toml;
 
@@ -99,8 +99,8 @@ fn get_name<'a>(path: &'a Path, opts: &'a NewOptions, config: &Config) -> CargoR
     }
 
     let dir_name = path.file_name().and_then(|s| s.to_str()).ok_or_else(|| {
-        human(&format!("cannot create a project with a non-unicode name: {:?}",
-                       path.file_name().unwrap()))
+        CargoError::from(format!("cannot create a project with a non-unicode name: {:?}",
+                                 path.file_name().unwrap()))
     })?;
 
     if opts.bin {
@@ -236,10 +236,10 @@ cannot automatically generate Cargo.toml as the main target would be ambiguous",
             duplicates_checker.insert(i.target_name.as_ref(), i);
         } else {
             if let Some(plp) = previous_lib_relpath {
-                return Err(human(format!("cannot have a project with \
-                                         multiple libraries, \
-                                         found both `{}` and `{}`",
-                                         plp, i.relative_path)));
+                return Err(format!("cannot have a project with \
+                                    multiple libraries, \
+                                    found both `{}` and `{}`",
+                                   plp, i.relative_path).into());
             }
             previous_lib_relpath = Some(&i.relative_path);
         }
@@ -287,8 +287,8 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
     };
 
     mk(config, &mkopts).chain_err(|| {
-        human(format!("Failed to create project `{}` at `{}`",
-                      name, path.display()))
+        format!("Failed to create project `{}` at `{}`",
+                name, path.display())
     })
 }
 
@@ -358,8 +358,8 @@ pub fn init(opts: NewOptions, config: &Config) -> CargoResult<()> {
     };
 
     mk(config, &mkopts).chain_err(|| {
-        human(format!("Failed to create project `{}` at `{}`",
-                      name, path.display()))
+        format!("Failed to create project `{}` at `{}`",
+                 name, path.display())
     })
 }
 
index f9a070797bc1534377adb115da4428f34e017fc1..c46c7b2eeeb220c41e454c3f3408b31297f0648f 100644 (file)
@@ -11,7 +11,7 @@ use tar::{Archive, Builder, Header, EntryType};
 
 use core::{Package, Workspace, Source, SourceId};
 use sources::PathSource;
-use util::{self, human, internal, Config, FileLock};
+use util::{self, internal, Config, FileLock};
 use util::errors::{CargoResult, CargoResultExt};
 use ops::{self, DefaultExecutor};
 
@@ -69,12 +69,12 @@ pub fn package(ws: &Workspace,
     config.shell().status("Packaging", pkg.package_id().to_string())?;
     dst.file().set_len(0)?;
     tar(ws, &src, dst.file(), &filename).chain_err(|| {
-        human("failed to prepare local package for uploading")
+        "failed to prepare local package for uploading"
     })?;
     if opts.verify {
         dst.seek(SeekFrom::Start(0))?;
         run_verify(ws, dst.file(), opts).chain_err(|| {
-            human("failed to verify package tarball")
+            "failed to verify package tarball"
         })?
     }
     dst.seek(SeekFrom::Start(0))?;
@@ -82,7 +82,7 @@ pub fn package(ws: &Workspace,
         let src_path = dst.path();
         let dst_path = dst.parent().join(&filename);
         fs::rename(&src_path, &dst_path).chain_err(|| {
-            human("failed to move temporary tarball into final location")
+            "failed to move temporary tarball into final location"
         })?;
     }
     Ok(Some(dst))
@@ -200,8 +200,8 @@ fn tar(ws: &Workspace,
         let relative = util::without_prefix(&file, &root).unwrap();
         check_filename(relative)?;
         let relative = relative.to_str().ok_or_else(|| {
-            human(format!("non-utf8 path in source directory: {}",
-                          relative.display()))
+            format!("non-utf8 path in source directory: {}",
+                    relative.display())
         })?;
         config.shell().verbose(|shell| {
             shell.status("Archiving", &relative)
@@ -229,13 +229,13 @@ fn tar(ws: &Workspace,
         // look at rust-lang/cargo#2326
         let mut header = Header::new_ustar();
         header.set_path(&path).chain_err(|| {
-            human(format!("failed to add to archive: `{}`", relative))
+            format!("failed to add to archive: `{}`", relative)
         })?;
         let mut file = File::open(file).chain_err(|| {
-            human(format!("failed to open for archiving: `{}`", file.display()))
+            format!("failed to open for archiving: `{}`", file.display())
         })?;
         let metadata = file.metadata().chain_err(|| {
-            human(format!("could not learn metadata for: `{}`", relative))
+            format!("could not learn metadata for: `{}`", relative)
         })?;
         header.set_metadata(&metadata);
 
index 4933e0ea672d9056639c0587cb26649d6d99107f..98cfde1d38974d7b9ad48bce5477542757db0ca4 100644 (file)
@@ -4,7 +4,7 @@ use std::io;
 use std::path::{Path, PathBuf};
 
 use core::{Package, SourceId, PackageId, EitherManifest};
-use util::{self, paths, human, Config};
+use util::{self, paths, Config};
 use util::errors::{CargoResult, CargoResultExt};
 use util::important_paths::find_project_manifest_exact;
 use util::toml::Layout;
@@ -17,8 +17,8 @@ pub fn read_manifest(path: &Path, source_id: &SourceId, config: &Config)
     let layout = Layout::from_project_path(path.parent().unwrap());
     let root = layout.root.clone();
     util::toml::to_manifest(&contents, source_id, layout, config).chain_err(|| {
-        human(format!("failed to parse manifest at `{}`",
-                      root.join("Cargo.toml").display()))
+        format!("failed to parse manifest at `{}`",
+                root.join("Cargo.toml").display())
     })
 }
 
@@ -74,7 +74,7 @@ pub fn read_packages(path: &Path, source_id: &SourceId, config: &Config)
     })?;
 
     if all_packages.is_empty() {
-        Err(human(format!("Could not find Cargo.toml in `{}`", path.display())))
+        Err(format!("Could not find Cargo.toml in `{}`", path.display()).into())
     } else {
         Ok(all_packages.into_iter().map(|(_, v)| v).collect())
     }
@@ -95,8 +95,8 @@ fn walk(path: &Path, callback: &mut FnMut(&Path) -> CargoResult<bool>)
             return Ok(())
         }
         Err(e) => {
-            return Err(human(e)).chain_err(|| {
-                human(format!("failed to read directory `{}`", path.display()))
+            return Err(e).chain_err(|| {
+                format!("failed to read directory `{}`", path.display())
             })
         }
     };
index 2c823e21977458219cdc6cae95a16b6d1d9289e3..85fd9a3df21b4d7eea92b642033b6b4e66305680 100644 (file)
@@ -1,7 +1,7 @@
 use std::path::Path;
 
 use ops::{self, Packages};
-use util::{self, human, CargoResult, CargoError, ProcessError};
+use util::{self, CargoResult, CargoError, ProcessError};
 use util::errors::CargoErrorKind;
 use core::Workspace;
 
@@ -16,9 +16,10 @@ pub fn run(ws: &Workspace,
             0 => ws.current()?,
             1 => ws.members()
                 .find(|pkg| pkg.name() == xs[0])
-                .ok_or_else(|| human(
-                    format!("package `{}` is not a member of the workspace", xs[0])
-                ))?,
+                .ok_or_else(|| 
+                    CargoError::from(
+                        format!("package `{}` is not a member of the workspace", xs[0]))
+                )?,
             _ => unreachable!("cargo run supports single package only"),
         }
     };
index 9076b80a60baf72282ea3b8a94e8b14cd2fd2bf6..f78e67049a721b59372fafcf403e4366fcaaa8ce 100644 (file)
@@ -11,7 +11,7 @@ use std::sync::Arc;
 use core::{Package, PackageId, PackageSet, Resolve, Target, Profile};
 use core::{TargetKind, Profiles, Dependency, Workspace};
 use core::dependency::Kind as DepKind;
-use util::{self, internal, Config, profile, Cfg, CfgExpr, human};
+use util::{self, internal, Config, profile, Cfg, CfgExpr};
 use util::errors::{CargoResult, CargoResultExt};
 
 use super::TargetConfig;
@@ -215,8 +215,8 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
             has_cfg_and_sysroot = false;
             process.exec_with_output()
         }).chain_err(|| {
-            human(format!("failed to run `rustc` to learn about \
-                           target-specific information"))
+            format!("failed to run `rustc` to learn about \
+                     target-specific information")
         })?;
 
         let error = str::from_utf8(&output.stderr).unwrap();
index 1be9d884e95fee9084cccf45077ef92ad8d9f1cf..816bbe154b9865278705d0a94818ae01ac79f9d8 100644 (file)
@@ -509,7 +509,7 @@ fn compare_old_fingerprint(loc: &Path, new_fingerprint: &Fingerprint)
 
     let old_fingerprint_json = paths::read(&loc.with_extension("json"))?;
     let old_fingerprint = serde_json::from_str(&old_fingerprint_json)
-        .chain_err(|| {internal(format!("failed to deserialize json"))})?;
+        .chain_err(|| internal(format!("failed to deserialize json")))?;
     new_fingerprint.compare(&old_fingerprint)
 }
 
index 2014b300934b4f626c8acdd28754c832f704136e..bfa374780d3ac41cc8fad72a31015eab0b7b394f 100644 (file)
@@ -9,7 +9,7 @@ use term::color::YELLOW;
 
 use core::{PackageId, Target, Profile};
 use util::{Config, DependencyQueue, Fresh, Dirty, Freshness};
-use util::{CargoResult, ProcessBuilder, profile, internal, human};
+use util::{CargoResult, ProcessBuilder, profile, internal};
 use {handle_error};
 
 use super::{Context, Kind, Unit};
@@ -186,7 +186,7 @@ impl<'a> JobQueue<'a> {
                             self.emit_warnings(Some(msg), key, cx)?;
 
                             if self.active > 0 {
-                                error = Some(human("build failed"));
+                                error = Some("build failed".into());
                                 handle_error(e, &mut *cx.config.shell());
                                 cx.config.shell().say(
                                             "Build failed, waiting for other \
index 66882e628a28405f632739b42b65ecb1f42c92dd..83c66e85a07e94401211b04d7907dbed4aac41d0 100644 (file)
@@ -54,7 +54,7 @@ use std::io;
 use std::path::{PathBuf, Path};
 
 use core::Workspace;
-use util::{Config, FileLock, CargoResult, Filesystem, human};
+use util::{Config, FileLock, CargoResult, Filesystem};
 
 pub struct Layout {
     root: PathBuf,
@@ -83,7 +83,7 @@ impl Layout {
         // the target triple as a Path and then just use the file stem as the
         // component for the directory name.
         if let Some(triple) = triple {
-            path.push(Path::new(triple).file_stem().ok_or(human("target was empty".to_string()))?);
+            path.push(Path::new(triple).file_stem().ok_or_else(|| "target was empty")?);
         }
         path.push(dest);
         Layout::at(ws.config(), path)
index 1e2aad9ccd5da29045579234803ee534aa733841..f52811dbd4eacad3ac0cf8c7c0e23e2f8fa10b2c 100644 (file)
@@ -11,7 +11,7 @@ use serde_json;
 use core::{Package, PackageId, PackageSet, Target, Resolve};
 use core::{Profile, Profiles, Workspace};
 use core::shell::ColorConfig;
-use util::{self, ProcessBuilder, human, machine_message};
+use util::{self, ProcessBuilder, machine_message};
 use util::{Config, internal, profile, join_paths, short_hash};
 use util::errors::{CargoResult, CargoResultExt};
 use util::Freshness;
@@ -335,7 +335,7 @@ fn rustc(cx: &mut Context, unit: &Unit, exec: Arc<Executor>) -> CargoResult<Work
             for dst in &dsts {
                 if fs::metadata(dst).is_ok() {
                     fs::remove_file(dst).chain_err(|| {
-                        human(format!("Could not remove file: {}.", dst.display()))
+                        format!("Could not remove file: {}.", dst.display())
                     })?;
                 }
             }
@@ -369,11 +369,11 @@ fn rustc(cx: &mut Context, unit: &Unit, exec: Arc<Executor>) -> CargoResult<Work
                     Ok(())
                 }
             ).chain_err(|| {
-                human(format!("Could not compile `{}`.", name))
+                format!("Could not compile `{}`.", name)
             })?;
         } else {
             exec.exec(rustc, &package_id).map_err(|e| e.to_internal()).chain_err(|| {
-                human(format!("Could not compile `{}`.", name))
+                format!("Could not compile `{}`.", name)
             })?;
         }
 
@@ -482,7 +482,7 @@ fn link_targets(cx: &mut Context, unit: &Unit, fresh: bool) -> CargoResult<Work>
             debug!("linking {} to {}", src.display(), dst.display());
             if dst.exists() {
                 fs::remove_file(&dst).chain_err(|| {
-                    human(format!("failed to remove: {}", dst.display()))
+                    format!("failed to remove: {}", dst.display())
                 })?;
             }
             fs::hard_link(src, dst)
@@ -491,8 +491,8 @@ fn link_targets(cx: &mut Context, unit: &Unit, fresh: bool) -> CargoResult<Work>
                      fs::copy(src, dst).map(|_| ())
                  })
                  .chain_err(|| {
-                     human(format!("failed to link or copy `{}` to `{}`",
-                                   src.display(), dst.display()))
+                     format!("failed to link or copy `{}` to `{}`",
+                             src.display(), dst.display())
             })?;
         }
 
@@ -628,9 +628,7 @@ fn rustdoc(cx: &mut Context, unit: &Unit) -> CargoResult<Work> {
             }
         }
         state.running(&rustdoc);
-        rustdoc.exec().chain_err(|| {
-            human(format!("Could not document `{}`.", name))
-        })
+        rustdoc.exec().chain_err(|| format!("Could not document `{}`.", name))
     }))
 }
 
index 145b6fc41529c1583be40c9ef8791a539083847c..86e4317330211f3ccbf86bd4c3d57bf67490fecd 100644 (file)
@@ -101,11 +101,20 @@ fn run_unit_tests(options: &TestOptions,
             shell.status("Running", cmd.to_string())
         })?;
 
-        if let Err(CargoError(CargoErrorKind::ProcessErrorKind(e), .. )) = cmd.exec() {
-            errors.push(e);
-            if !options.no_fail_fast {
-                return Ok((Test::UnitTest(kind.clone(), test.clone()), errors))
+        let result = cmd.exec();
+
+        match result {
+            Err(CargoError(CargoErrorKind::ProcessErrorKind(e), .. )) => {
+                 errors.push(e);
+                if !options.no_fail_fast {
+                    return Ok((Test::UnitTest(kind.clone(), test.clone()), errors))
+                }
+            }
+            Err(e) => {
+                //This is an unexpected Cargo error rather than a test failure
+                return Err(e)
             }
+            Ok(()) => {}
         }
     }
     Ok((Test::Multiple, errors))
index 2f7bedb8b0c78fff63d471a60bd1b4cd53d030ea..1138be745e1292c06f3fea4cafe4557f53f90869 100644 (file)
@@ -4,7 +4,7 @@ use toml;
 
 use core::{Resolve, resolver, Workspace};
 use core::resolver::WorkspaceResolve;
-use util::{human, Filesystem};
+use util::Filesystem;
 use util::errors::{CargoResult, CargoResultExt};
 use util::toml as cargo_toml;
 
@@ -18,7 +18,7 @@ pub fn load_pkg_lockfile(ws: &Workspace) -> CargoResult<Option<Resolve>> {
 
     let mut s = String::new();
     f.read_to_string(&mut s).chain_err(|| {
-        human(format!("failed to read file: {}", f.path().display()))
+        format!("failed to read file: {}", f.path().display())
     })?;
 
     (|| -> CargoResult<Option<Resolve>> {
@@ -26,7 +26,7 @@ pub fn load_pkg_lockfile(ws: &Workspace) -> CargoResult<Option<Resolve>> {
         let v: resolver::EncodableResolve = resolve.try_into()?;
         Ok(Some(v.into_resolve(ws)?))
     })().chain_err(|| {
-        human(format!("failed to parse lock file at: {}", f.path().display()))
+        format!("failed to parse lock file at: {}", f.path().display())
     })
 }
 
@@ -100,8 +100,8 @@ pub fn write_pkg_lockfile(ws: &Workspace, resolve: &Resolve) -> CargoResult<()>
         f.write_all(out.as_bytes())?;
         Ok(())
     }).chain_err(|| {
-        human(format!("failed to write {}",
-                      ws.root().join("Cargo.lock").display()))
+        format!("failed to write {}",
+                ws.root().join("Cargo.lock").display())
     })
 }
 
index 4d55a84ad51c49cb27ac3219a3a25bf88d7a8bc3..6496715631fb0996f1b53ce609a76f69fc01b4eb 100644 (file)
@@ -21,9 +21,9 @@ use ops;
 use sources::{RegistrySource};
 use util::config;
 use util::paths;
-use util::{human, ToUrl};
+use util::ToUrl;
 use util::config::{Config, ConfigValue, Location};
-use util::errors::{CargoResult, CargoResultExt};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 use util::important_paths::find_root_manifest_for_wd;
 
 pub struct RegistryConfig {
@@ -176,7 +176,7 @@ fn transmit(config: &Config,
 
             Ok(())
         },
-        Err(e) => Err(human(e.to_string())),
+        Err(e) => Err(e.into()),
     }
 }
 
@@ -202,7 +202,7 @@ pub fn registry(config: &Config,
     let api_host = {
         let mut src = RegistrySource::remote(&sid, config);
         src.update().chain_err(|| {
-            human(format!("failed to update {}", sid))
+            format!("failed to update {}", sid)
         })?;
         (src.config()?).unwrap().api
     };
@@ -324,7 +324,7 @@ pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
         config.shell().status("Owner", format!("adding {:?} to crate {}",
                                                     v, name))?;
         registry.add_owners(&name, &v).map_err(|e| {
-            human(format!("failed to add owners to crate {}: {}", name, e))
+            CargoError::from(format!("failed to add owners to crate {}: {}", name, e))
         })?;
     }
 
@@ -333,13 +333,13 @@ pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
         config.shell().status("Owner", format!("removing {:?} from crate {}",
                                                     v, name))?;
         registry.remove_owners(&name, &v).map_err(|e| {
-            human(format!("failed to remove owners from crate {}: {}", name, e))
+            CargoError::from(format!("failed to remove owners from crate {}: {}", name, e))
         })?;
     }
 
     if opts.list {
         let owners = registry.list_owners(&name).map_err(|e| {
-            human(format!("failed to list owners of crate {}: {}", name, e))
+            CargoError::from(format!("failed to list owners of crate {}: {}", name, e))
         })?;
         for owner in owners.iter() {
             print!("{}", owner.login);
@@ -379,12 +379,12 @@ pub fn yank(config: &Config,
     if undo {
         config.shell().status("Unyank", format!("{}:{}", name, version))?;
         registry.unyank(&name, &version).map_err(|e| {
-            human(format!("failed to undo a yank: {}", e))
+            CargoError::from(format!("failed to undo a yank: {}", e))
         })?;
     } else {
         config.shell().status("Yank", format!("{}:{}", name, version))?;
         registry.yank(&name, &version).map_err(|e| {
-            human(format!("failed to yank: {}", e))
+            CargoError::from(format!("failed to yank: {}", e))
         })?;
     }
 
@@ -405,7 +405,7 @@ pub fn search(query: &str,
 
     let (mut registry, _) = registry(config, None, index)?;
     let (crates, total_crates) = registry.search(query, limit).map_err(|e| {
-        human(format!("failed to retrieve search results from the registry: {}", e))
+        CargoError::from(format!("failed to retrieve search results from the registry: {}", e))
     })?;
 
     let list_items = crates.iter()
index ca3b87b096cd652befe9b9c6b58a95cfe2a84471..8741c74259c4a315c24f10b5eed92e2b10a2286f 100644 (file)
@@ -5,7 +5,7 @@ use core::registry::PackageRegistry;
 use core::resolver::{self, Resolve, Method};
 use sources::PathSource;
 use ops;
-use util::{profile, human};
+use util::profile;
 use util::errors::{CargoResult, CargoResultExt};
 
 /// Resolve all dependencies for the workspace using the previous
@@ -263,9 +263,9 @@ fn add_overrides<'a>(registry: &mut PackageRegistry<'a>,
         let id = SourceId::for_path(&path)?;
         let mut source = PathSource::new_recursive(&path, &id, ws.config());
         source.update().chain_err(|| {
-            human(format!("failed to update path override `{}` \
+            format!("failed to update path override `{}` \
                            (defined in `{}`)", path.display(),
-                          definition.display()))
+                          definition.display())
         })?;
         registry.add_override(Box::new(source));
     }
index 4551c7c5976c4b8de3e5322e5693fc0bc4e7f465..8799f0c30e8774340702ff1f3558e6caa9707bde 100644 (file)
@@ -11,9 +11,9 @@ use url::Url;
 
 use core::{Source, SourceId};
 use sources::ReplacedSource;
-use util::{Config, human, ToUrl};
+use util::{Config, ToUrl};
 use util::config::ConfigValue;
-use util::errors::{CargoResult, CargoResultExt};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 
 pub struct SourceConfigMap<'cfg> {
     cfgs: HashMap<String, SourceConfig>,
@@ -157,13 +157,13 @@ a lock file compatible with `{orig}` cannot be generated in this situation
 
         let mut srcs = srcs.into_iter();
         let src = srcs.next().ok_or_else(|| {
-            human(format!("no source URL specified for `source.{}`, need \
-                           either `registry` or `local-registry` defined",
-                          name))
+            CargoError::from(format!("no source URL specified for `source.{}`, need \
+                                      either `registry` or `local-registry` defined",
+                                     name))
         })?;
         if srcs.next().is_some() {
-            return Err(human(format!("more than one source URL specified for \
-                                      `source.{}`", name)))
+            return Err(format!("more than one source URL specified for \
+                                `source.{}`", name).into())
         }
 
         let mut replace_with = None;
@@ -183,8 +183,8 @@ a lock file compatible with `{orig}` cannot be generated in this situation
         fn url(cfg: &ConfigValue, key: &str) -> CargoResult<Url> {
             let (url, path) = cfg.string(key)?;
             url.to_url().chain_err(|| {
-                human(format!("configuration key `{}` specified an invalid \
-                               URL (in {})", key, path.display()))
+                format!("configuration key `{}` specified an invalid \
+                         URL (in {})", key, path.display())
 
             })
         }
index 40dea56c46662ce0b64431fe15970374e0effa15..5117dfa17616c9525b5335df9e96b6e8a8568d9c 100644 (file)
@@ -9,8 +9,8 @@ use serde_json;
 
 use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
 use sources::PathSource;
-use util::{human, Config, Sha256};
-use util::errors::{CargoResult, CargoResultExt, CargoError};
+use util::{Config, Sha256};
+use util::errors::{CargoResult, CargoResultExt};
 use util::paths;
 
 pub struct DirectorySource<'cfg> {
@@ -65,8 +65,8 @@ impl<'cfg> Source for DirectorySource<'cfg> {
     fn update(&mut self) -> CargoResult<()> {
         self.packages.clear();
         let entries = self.root.read_dir().chain_err(|| {
-            human(format!("failed to read root of directory source: {}",
-                          self.root.display()))
+            format!("failed to read root of directory source: {}",
+                    self.root.display())
         })?;
 
         for entry in entries {
@@ -114,18 +114,18 @@ impl<'cfg> Source for DirectorySource<'cfg> {
 
             let cksum_file = path.join(".cargo-checksum.json");
             let cksum = paths::read(&path.join(cksum_file)).chain_err(|| {
-                human(format!("failed to load checksum `.cargo-checksum.json` \
-                               of {} v{}",
-                              pkg.package_id().name(),
-                              pkg.package_id().version()))
+                format!("failed to load checksum `.cargo-checksum.json` \
+                         of {} v{}",
+                        pkg.package_id().name(),
+                        pkg.package_id().version())
 
             })?;
             let cksum: Checksum = serde_json::from_str(&cksum)
-                .map_err(CargoError::from).chain_err(|| {
-                human(format!("failed to decode `.cargo-checksum.json` of \
-                               {} v{}",
-                              pkg.package_id().name(),
-                              pkg.package_id().version()))
+                .chain_err(|| {
+                format!("failed to decode `.cargo-checksum.json` of \
+                         {} v{}",
+                        pkg.package_id().name(),
+                        pkg.package_id().version())
             })?;
 
             let mut manifest = pkg.manifest().clone();
@@ -140,7 +140,7 @@ impl<'cfg> Source for DirectorySource<'cfg> {
 
     fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
         self.packages.get(id).map(|p| &p.0).cloned().ok_or_else(|| {
-            human(format!("failed to find package with id: {}", id))
+            format!("failed to find package with id: {}", id).into()
         })
     }
 
@@ -169,8 +169,8 @@ impl<'cfg> Source for DirectorySource<'cfg> {
                     }
                 }
             })().chain_err(|| {
-                human(format!("failed to calculate checksum of: {}",
-                              file.display()))
+                format!("failed to calculate checksum of: {}",
+                        file.display())
             })?;
 
             let actual = h.finish().to_hex();
index d7f5e6852d0f658a2a19a00f1cc1d56946bbaa8a..9052f7a14a800a15873fa9dc13123a1dee9a1399 100644 (file)
@@ -8,7 +8,7 @@ use serde::ser::{self, Serialize};
 use url::Url;
 
 use core::GitReference;
-use util::{human, ToUrl, internal, Config, network};
+use util::{ToUrl, internal, Config, network};
 use util::errors::{CargoResult, CargoResultExt, CargoError};
 
 #[derive(PartialEq, Clone, Debug)]
@@ -92,13 +92,13 @@ impl GitRemote {
         let repo = match git2::Repository::open(into) {
             Ok(repo) => {
                 self.fetch_into(&repo, cargo_config).chain_err(|| {
-                    human(format!("failed to fetch into {}", into.display()))
+                    format!("failed to fetch into {}", into.display())
                 })?;
                 repo
             }
             Err(..) => {
                 self.clone_into(into, cargo_config).chain_err(|| {
-                    human(format!("failed to clone into: {}", into.display()))
+                    format!("failed to clone into: {}", into.display())
                 })?
             }
         };
@@ -133,7 +133,7 @@ impl GitRemote {
         }
         fs::create_dir_all(dst)?;
         let repo = git2::Repository::init_bare(dst)?;
-        fetch(&repo, &url, "refs/heads/*:refs/heads/*", cargo_config)?;            
+        fetch(&repo, &url, "refs/heads/*:refs/heads/*", cargo_config)?;
         Ok(repo)
     }
 }
@@ -171,17 +171,17 @@ impl GitDatabase {
                     let obj = obj.peel(ObjectType::Commit)?;
                     Ok(obj.id())
                 })().chain_err(|| {
-                    human(format!("failed to find tag `{}`", s))
+                    format!("failed to find tag `{}`", s)
                 })?
             }
             GitReference::Branch(ref s) => {
                 (|| {
                     let b = self.repo.find_branch(s, git2::BranchType::Local)?;
                     b.get().target().ok_or_else(|| {
-                        human(format!("branch `{}` did not have a target", s))
+                        CargoError::from(format!("branch `{}` did not have a target", s))
                     })
                 })().chain_err(|| {
-                    human(format!("failed to find branch `{}`", s))
+                    format!("failed to find branch `{}`", s)
                 })?
             }
             GitReference::Rev(ref s) => {
@@ -232,20 +232,19 @@ impl<'a> GitCheckout<'a> {
     fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> {
         let dirname = into.parent().unwrap();
 
-        fs::create_dir_all(&dirname).map_err(CargoError::from).chain_err(|| {
-            human(format!("Couldn't mkdir {}", dirname.display()))
+        fs::create_dir_all(&dirname).chain_err(|| {
+            format!("Couldn't mkdir {}", dirname.display())
         })?;
 
         if fs::metadata(&into).is_ok() {
-            fs::remove_dir_all(into).map_err(CargoError::from).chain_err(|| {
-                human(format!("Couldn't rmdir {}", into.display()))
+            fs::remove_dir_all(into).chain_err(|| {
+                format!("Couldn't rmdir {}", into.display())
             })?;
         }
 
         let url = source.to_url()?;
         let url = url.to_string();
         let repo = git2::Repository::clone(&url, into)            
-            .map_err(CargoError::from)
             .chain_err(|| {
                 internal(format!("failed to clone {} into {}", source.display(),
                              into.display()))
@@ -284,8 +283,8 @@ impl<'a> GitCheckout<'a> {
         let ok_file = self.location.join(".cargo-ok");
         let _ = fs::remove_file(&ok_file);
         info!("reset {} to {}", self.repo.path().display(), self.revision);
-        self.repo.find_object(self.revision.0, None)
-            .and_then(|obj| {self.repo.reset(&obj, git2::ResetType::Hard, None)})?;
+        let object = self.repo.find_object(self.revision.0, None)?;
+        self.repo.reset(&object, git2::ResetType::Hard, None)?;
         File::create(ok_file)?;
         Ok(())
     }
@@ -298,8 +297,8 @@ impl<'a> GitCheckout<'a> {
 
             for mut child in repo.submodules()?.into_iter() {
                 update_submodule(repo, &mut child, cargo_config).chain_err(|| {
-                    human(format!("failed to update submodule `{}`",
-                                  child.name().unwrap_or("")))
+                    format!("failed to update submodule `{}`",
+                            child.name().unwrap_or(""))
                 })?;
             }
             Ok(())
@@ -552,7 +551,7 @@ fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F)
                               credentials were incorrect");
             }
         }
-        human(msg)
+        msg
     })
 }
 
@@ -577,7 +576,7 @@ pub fn fetch(repo: &git2::Repository,
 
         network::with_retry(config, || {
             remote.fetch(&[refspec], Some(&mut opts), None)
-                .map_err(network::NetworkError::from)
+                .map_err(CargoError::from)
         })?;
         Ok(())
     })
index b50a2fd3e1046607daaa5e8a4b976cb99f7af5d5..dd27076cf5d17690ce9ca43807f389c20caa66c3 100644 (file)
@@ -8,7 +8,7 @@ use glob::Pattern;
 
 use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
 use ops;
-use util::{self, CargoResult, internal, internal_error, human};
+use util::{self, CargoError, CargoResult, internal};
 use util::Config;
 
 pub struct PathSource<'cfg> {
@@ -90,7 +90,7 @@ impl<'cfg> PathSource<'cfg> {
 
         let parse = |p: &String| {
             Pattern::new(p).map_err(|e| {
-                human(format!("could not parse pattern `{}`: {}", p, e))
+                CargoError::from(format!("could not parse pattern `{}`: {}", p, e))
             })
         };
 
@@ -155,7 +155,7 @@ impl<'cfg> PathSource<'cfg> {
         warn!("list_files_git {}", pkg.package_id());
         let index = repo.index()?;
         let root = repo.workdir().ok_or_else(|| {
-            internal_error("Can't list files on a bare repository.", "")
+            internal("Can't list files on a bare repository.")
         })?;
         let pkg_path = pkg.root();
 
@@ -231,7 +231,7 @@ impl<'cfg> PathSource<'cfg> {
                 warn!("  found submodule {}", file_path.display());
                 let rel = util::without_prefix(&file_path, root).unwrap();
                 let rel = rel.to_str().ok_or_else(|| {
-                    human(format!("invalid utf-8 filename: {}", rel.display()))
+                    CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
                 })?;
                 // Git submodules are currently only named through `/` path
                 // separators, explicitly not `\` which windows uses. Who knew?
@@ -348,7 +348,7 @@ impl<'cfg> Source for PathSource<'cfg> {
 
     fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
         if !self.updated {
-            return Err(internal_error("BUG: source was not updated", ""));
+            return Err(internal("BUG: source was not updated"));
         }
 
         let mut max = FileTime::zero();
index d935ee73a0feb95f2e53a81483e90290a8348f37..5853774b20a9d5581ddc1cdc9129af2577eadf20 100644 (file)
@@ -8,8 +8,7 @@ use core::dependency::{Dependency, DependencyInner, Kind};
 use core::{SourceId, Summary, PackageId, Registry};
 use sources::registry::{RegistryPackage, RegistryDependency, INDEX_LOCK};
 use sources::registry::RegistryData;
-use util::{CargoResult, internal, Filesystem, Config};
-use util::human;
+use util::{CargoError, CargoResult, internal, Filesystem, Config};
 
 pub struct RegistryIndex<'cfg> {
     source_id: SourceId,
@@ -107,7 +106,7 @@ impl<'cfg> RegistryIndex<'cfg> {
         match load.load(&root, Path::new(&path)) {
             Ok(contents) => {
                 let contents = str::from_utf8(&contents).map_err(|_| {
-                    human("registry index file was not valid utf-8")
+                    CargoError::from("registry index file was not valid utf-8")
                 })?;
                 let lines = contents.lines()
                                     .map(|s| s.trim())
index 868e571c86eb5d2af8d79ed4bbdb83f082683c9a..ef23552caf1aab340efb4990345c6fb2dc1e7795 100644 (file)
@@ -8,7 +8,7 @@ use core::PackageId;
 use sources::registry::{RegistryData, RegistryConfig};
 use util::FileLock;
 use util::paths;
-use util::{Config, human, Sha256, Filesystem};
+use util::{Config, Sha256, Filesystem};
 use util::errors::{CargoResult, CargoResultExt};
 
 pub struct LocalRegistry<'cfg> {
@@ -85,7 +85,7 @@ impl<'cfg> RegistryData for LocalRegistry<'cfg> {
         let mut buf = [0; 64 * 1024];
         loop {
             let n = crate_file.read(&mut buf).chain_err(|| {
-                human(format!("failed to read `{}`", crate_file.path().display()))
+                format!("failed to read `{}`", crate_file.path().display())
             })?;
             if n == 0 {
                 break
index 9661d4490efc0e8cfd22c7bd488488f7c7ef7ea5..cddbda2ed628af0d9d828699e9ff0222fa7ada73 100644 (file)
@@ -16,8 +16,8 @@ use sources::git;
 use sources::registry::{RegistryData, RegistryConfig, INDEX_LOCK};
 use util::network;
 use util::{FileLock, Filesystem, LazyCell};
-use util::{Config, human, Sha256, ToUrl};
-use util::errors::{CargoResult, CargoResultExt};
+use util::{Config, Sha256, ToUrl};
+use util::errors::{CargoErrorKind, CargoResult, CargoResultExt};
 
 pub struct RemoteRegistry<'cfg> {
     index_path: Filesystem,
@@ -190,7 +190,7 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
             let url = self.source_id.url().to_string();
             let refspec = "refs/heads/master:refs/remotes/origin/master";
             git::fetch(&repo, &url, refspec, self.config).chain_err(|| {
-                human(format!("failed to fetch `{}`", url))
+                format!("failed to fetch `{}`", url)
             })?;
         }
 
@@ -255,7 +255,7 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
             let code = handle.response_code()?;
             if code != 200 && code != 0 {
                 let url = handle.effective_url()?.unwrap_or(&url);
-                Err(network::NetworkErrorKind::HttpNot200(code, url.to_string()).into())
+                Err(CargoErrorKind::HttpNot200(code, url.to_string()).into())
             } else {
                 Ok(())
             }
index befb37ce519cb75749f65abcd28f79ccd36ccf42..47d9feb68addfa46dca308f134fe4c2c885c8f3e 100644 (file)
@@ -1,6 +1,5 @@
 use core::{Source, Registry, PackageId, Package, Dependency, Summary, SourceId};
-use util::{CargoResult, human};
-use util::errors::CargoResultExt;
+use util::errors::{CargoResult, CargoResultExt};
 
 pub struct ReplacedSource<'cfg> {
     to_replace: SourceId,
@@ -24,8 +23,8 @@ impl<'cfg> Registry for ReplacedSource<'cfg> {
     fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
         let dep = dep.clone().map_source(&self.to_replace, &self.replace_with);
         let ret = self.inner.query(&dep).chain_err(|| {
-            human(format!("failed to query replaced source `{}`",
-                          self.to_replace))
+            format!("failed to query replaced source `{}`",
+                    self.to_replace)
         })?;
         Ok(ret.into_iter().map(|summary| {
             summary.map_source(&self.replace_with, &self.to_replace)
@@ -40,16 +39,16 @@ impl<'cfg> Source for ReplacedSource<'cfg> {
 
     fn update(&mut self) -> CargoResult<()> {
         self.inner.update().chain_err(|| {
-            human(format!("failed to update replaced source `{}`",
-                          self.to_replace))
+            format!("failed to update replaced source `{}`",
+                    self.to_replace)
         })
     }
 
     fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
         let id = id.with_source_id(&self.replace_with);
         let pkg = self.inner.download(&id).chain_err(|| {
-            human(format!("failed to download replaced source `{}`",
-                          self.to_replace))
+            format!("failed to download replaced source `{}`",
+                    self.to_replace)
         })?;
         Ok(pkg.map_source(&self.replace_with, &self.to_replace))
     }
index 10455a960489d74befffb9b5641109389eb6b66b..341b24d6d939a1fac5f1738613b41c078d2f1ed9 100644 (file)
@@ -2,7 +2,7 @@ use std::str::{self, FromStr};
 use std::iter;
 use std::fmt;
 
-use util::{CargoError, CargoResult, human};
+use util::{CargoError, CargoResult};
 
 #[derive(Clone, PartialEq, Debug)]
 pub enum Cfg {
@@ -215,7 +215,7 @@ impl<'a> Iterator for Tokenizer<'a> {
                             return Some(Ok(Token::String(&self.orig[start+1..end])))
                         }
                     }
-                    return Some(Err(human("unterminated string in cfg".to_string())))
+                    return Some(Err("unterminated string in cfg".into()))
                 }
                 Some((start, ch)) if is_ident_start(ch) => {
                     while let Some(&(end, ch)) = self.s.peek() {
@@ -228,10 +228,10 @@ impl<'a> Iterator for Tokenizer<'a> {
                     return Some(Ok(Token::Ident(&self.orig[start..])))
                 }
                 Some((_, ch)) => {
-                    return Some(Err(human(format!("unexpected character in \
+                    return Some(Err(format!("unexpected character in \
                                                    cfg `{}`, expected parens, \
                                                    a comma, an identifier, or \
-                                                   a string", ch))))
+                                                   a string", ch).into()))
                 }
                 None => return None
             }
index 120980eede86acfeb9ac7507d96bd9e913c2a2b1..afaacae0674ef4fca5c9370b65e7c9912b2acc19 100644 (file)
@@ -15,8 +15,8 @@ use rustc_serialize::{Encodable,Encoder};
 use toml;
 use core::shell::{Verbosity, ColorConfig};
 use core::MultiShell;
-use util::{CargoResult, CargoError, Rustc, internal, human};
-use util::errors::CargoResultExt;
+use util::Rustc;
+use util::errors::{CargoResult, CargoResultExt, CargoError, internal};
 use util::{Filesystem, LazyCell};
 use util::paths;
 
@@ -58,11 +58,11 @@ impl Config {
     pub fn default() -> CargoResult<Config> {
         let shell = ::shell(Verbosity::Verbose, ColorConfig::Auto);
         let cwd = env::current_dir().chain_err(|| {
-            human("couldn't get the current directory of the process")
+            "couldn't get the current directory of the process"
         })?;
         let homedir = homedir(&cwd).ok_or_else(|| {
-            human("Cargo couldn't find your home directory. \
-                  This probably means that $HOME was not set.")
+            "Cargo couldn't find your home directory. \
+             This probably means that $HOME was not set."
         })?;
         Ok(Config::new(shell, cwd, homedir))
     }
@@ -101,9 +101,7 @@ impl Config {
     pub fn cargo_exe(&self) -> CargoResult<&Path> {
         self.cargo_exe.get_or_try_init(||
             env::current_exe().and_then(|path| path.canonicalize())
-            .chain_err(|| {
-                human("couldn't get the path to cargo executable")
-            })
+            .chain_err(|| "couldn't get the path to cargo executable")
         ).map(AsRef::as_ref)
     }
 
@@ -113,11 +111,11 @@ impl Config {
 
     pub fn set_values(&self, values: HashMap<String, ConfigValue>) -> CargoResult<()> {
         if self.values.borrow().is_some() {
-            return Err(human("Config values already found"));
+            return Err("Config values already found".into());
         }
         match self.values.fill(values) {
             Ok(()) => Ok(()),
-            Err(_) => Err(human("Could not fill values")),
+            Err(_) => Err("Could not fill values".into()),
         }
     }
 
@@ -342,7 +340,7 @@ impl Config {
 
     pub fn expected<T>(&self, ty: &str, key: &str, val: CV) -> CargoResult<T> {
         val.expected(ty, key).map_err(|e| {
-            human(format!("invalid configuration for key `{}`\n{}", key, e))
+            format!("invalid configuration for key `{}`\n{}", key, e).into()
         })
     }
 
@@ -412,25 +410,24 @@ impl Config {
         walk_tree(&self.cwd, |mut file, path| {
             let mut contents = String::new();
             file.read_to_string(&mut contents).chain_err(|| {
-                human(format!("failed to read configuration file `{}`",
-                              path.display()))
+                format!("failed to read configuration file `{}`",
+                         path.display())
             })?;
             let toml = cargo_toml::parse(&contents,
                                          &path,
                                          self).chain_err(|| {
-                human(format!("could not parse TOML configuration in `{}`",
-                              path.display()))
+                format!("could not parse TOML configuration in `{}`",
+                        path.display())
             })?;
             let value = CV::from_toml(&path, toml).chain_err(|| {
-                human(format!("failed to load TOML configuration from `{}`",
-                              path.display()))
+                format!("failed to load TOML configuration from `{}`",
+                        path.display())
             })?;
             cfg.merge(value).chain_err(|| {
-                human(format!("failed to merge configuration at `{}`",
-                              path.display()))
+                format!("failed to merge configuration at `{}`", path.display())
             })?;
             Ok(())
-        }).chain_err(|| human("Couldn't load Cargo configuration"))?;
+        }).chain_err(|| "Couldn't load Cargo configuration")?;
 
 
         match cfg {
@@ -535,15 +532,15 @@ impl ConfigValue {
                 Ok(CV::List(val.into_iter().map(|toml| {
                     match toml {
                         toml::Value::String(val) => Ok((val, path.to_path_buf())),
-                        v => Err(human(format!("expected string but found {} \
-                                                in list", v.type_str()))),
+                        v => Err(format!("expected string but found {} \
+                                                in list", v.type_str()).into()),
                     }
                 }).collect::<CargoResult<_>>()?, path.to_path_buf()))
             }
             toml::Value::Table(val) => {
                 Ok(CV::Table(val.into_iter().map(|(key, value)| {
                     let value = CV::from_toml(path, value).chain_err(|| {
-                        human(format!("failed to parse key `{}`", key))
+                        format!("failed to parse key `{}`", key)
                     })?;
                     Ok((key, value))
                 }).collect::<CargoResult<_>>()?, path.to_path_buf()))
@@ -570,13 +567,13 @@ impl ConfigValue {
                             let path = value.definition_path().to_path_buf();
                             let entry = entry.get_mut();
                             entry.merge(value).chain_err(|| {
-                                human(format!("failed to merge key `{}` between \
-                                               files:\n  \
-                                               file 1: {}\n  \
-                                               file 2: {}",
-                                              key,
-                                              entry.definition_path().display(),
-                                              path.display()))
+                                format!("failed to merge key `{}` between \
+                                         files:\n  \
+                                         file 1: {}\n  \
+                                         file 2: {}",
+                                        key,
+                                        entry.definition_path().display(),
+                                        path.display())
 
                             })?;
                         }
@@ -650,9 +647,9 @@ impl ConfigValue {
     }
 
     fn expected<T>(&self, wanted: &str, key: &str) -> CargoResult<T> {
-        Err(human(format!("expected a {}, but found a {} for `{}` in {}",
-                          wanted, self.desc(), key,
-                          self.definition_path().display())))
+        Err(format!("expected a {}, but found a {} for `{}` in {}",
+                    wanted, self.desc(), key,
+                    self.definition_path().display()).into())
     }
 
     fn into_toml(self) -> toml::Value {
@@ -759,8 +756,8 @@ fn walk_tree<F>(pwd: &Path, mut walk: F) -> CargoResult<()>
     // in our history to be sure we pick up that standard location for
     // information.
     let home = homedir(pwd).ok_or_else(|| {
-        human("Cargo couldn't find your home directory. \
-              This probably means that $HOME was not set.")
+        CargoError::from("Cargo couldn't find your home directory. \
+                          This probably means that $HOME was not set.")
     })?;
     let config = home.join("config");
     if !stash.contains(&config) && fs::metadata(&config).is_ok() {
index 2a98a807e785a4be163a0c1630ce6ac503c6546b..718e9619fa846f6f81775c46118b212b3c3df635 100644 (file)
@@ -7,7 +7,6 @@ use std::str;
 use std::string;
 
 use core::TargetKind;
-use util::network::{NetworkError, NetworkErrorKind};
 
 use curl;
 use git2;
@@ -15,6 +14,7 @@ use semver;
 use serde_json;
 use term;
 use toml;
+use registry;
 
 error_chain! {
     types {
@@ -22,11 +22,12 @@ error_chain! {
     }
 
     links {
-        Network(NetworkError, NetworkErrorKind);
+        CrateRegistry(registry::Error, registry::ErrorKind);
     }
 
     foreign_links {
         ParseSemver(semver::ReqParseError);
+        Semver(semver::SemVerError);
         Io(io::Error);
         SerdeJson(serde_json::Error);
         TomlSer(toml::ser::Error);
@@ -40,7 +41,7 @@ error_chain! {
     }
 
     errors {
-        Internal(description: String, details: Option<String>){
+        Internal(description: String){
             description(&description)
             display("{}", &description)
         }
@@ -52,12 +53,16 @@ error_chain! {
             description(&test_err.desc)
             display("{}", &test_err.desc)
         }
+        HttpNot200(code: u32, url: String) {
+            description("failed to get a 200 response")
+            display("failed to get 200 response from `{}`, got {}", url, code)
+        }
     }
 }
 
 impl CargoError {
     pub fn to_internal(self) -> Self {
-        CargoError(CargoErrorKind::Internal(self.description().to_string(), None), self.1)
+        CargoError(CargoErrorKind::Internal(self.description().to_string()), self.1)
     }
 
     fn is_human(&self) -> bool {
@@ -66,14 +71,20 @@ impl CargoError {
             &CargoErrorKind::TomlSer(_) => true,
             &CargoErrorKind::TomlDe(_) => true,
             &CargoErrorKind::Curl(_) => true,
-            &CargoErrorKind::Network(ref net_err) => {
-                match net_err {
-                    &NetworkErrorKind::HttpNot200(_, _) => true,
-                    &NetworkErrorKind::Curl(_) => true,
-                    _ => false
-                }
-            },
-            _ => false
+            &CargoErrorKind::HttpNot200(..) => true,
+            &CargoErrorKind::CrateRegistry(_) |
+            &CargoErrorKind::ParseSemver(_) |
+            &CargoErrorKind::Semver(_) |
+            &CargoErrorKind::Io(_) |
+            &CargoErrorKind::SerdeJson(_) |
+            &CargoErrorKind::Term(_) |
+            &CargoErrorKind::ParseInt(_) |
+            &CargoErrorKind::ParseBool(_) |
+            &CargoErrorKind::Parse(_) |
+            &CargoErrorKind::Git(_) |
+            &CargoErrorKind::Internal(_) |
+            &CargoErrorKind::ProcessErrorKind(_) |
+            &CargoErrorKind::CargoTestErrorKind(_) => false
         }
     }
 }
@@ -265,22 +276,10 @@ pub fn process_error(msg: &str,
     }
 }
 
-pub fn internal_error(error: &str, detail: &str) -> CargoError {
-    CargoErrorKind::Internal(error.to_string(), Some(detail.to_string())).into()
-}
-
 pub fn internal<S: fmt::Display>(error: S) -> CargoError {
     _internal(&error)
 }
 
 fn _internal(error: &fmt::Display) -> CargoError {
-    CargoErrorKind::Internal(error.to_string(), None).into()
-}
-
-pub fn human<S: fmt::Display>(error: S) -> CargoError {
-    _human(&error)
-}
-
-fn _human(error: &fmt::Display) -> CargoError {
-    CargoErrorKind::Msg(error.to_string()).into()
+    CargoErrorKind::Internal(error.to_string()).into()
 }
index a94a81e032ee039e260d133954d85fbd70d43025..a4621dbeae48733c4d4a868c3fe9d6630483e013 100644 (file)
@@ -8,7 +8,7 @@ use fs2::{FileExt, lock_contended_error};
 #[allow(unused_imports)]
 use libc;
 
-use util::{Config, human};
+use util::Config;
 use util::errors::{CargoResult, CargoResultExt};
 
 pub struct FileLock {
@@ -213,7 +213,7 @@ impl Filesystem {
                 Err(e)
             }
         }).chain_err(|| {
-            human(format!("failed to open: {}", path.display()))
+            format!("failed to open: {}", path.display())
         })?;
         match state {
             State::Exclusive => {
@@ -282,8 +282,8 @@ fn acquire(config: &Config,
 
         Err(e) => {
             if e.raw_os_error() != lock_contended_error().raw_os_error() {
-                return Err(human(e)).chain_err(|| {
-                    human(format!("failed to lock file: {}", path.display()))
+                return Err(e).chain_err(|| {
+                    format!("failed to lock file: {}", path.display())
                 })
             }
         }
@@ -292,7 +292,7 @@ fn acquire(config: &Config,
     config.shell().err().say_status("Blocking", &msg, CYAN, true)?;
 
     return block().chain_err(|| {
-        human(format!("failed to lock file: {}", path.display()))
+        format!("failed to lock file: {}", path.display())
     });
 
     #[cfg(all(target_os = "linux", not(target_env = "musl")))]
index 35161eaae1d6e5d23f79bf49b9d580fb4339edcc..069979ea97cc765686d623faae95d4a7f36b65af 100644 (file)
@@ -1,6 +1,6 @@
 use std::fs;
 use std::path::{Path, PathBuf};
-use util::{CargoResult, human};
+use util::errors::CargoResult;
 use util::paths;
 
 /// Iteratively search for `file` in `pwd` and its parents, returning
@@ -59,7 +59,7 @@ pub fn find_project_manifest_exact(pwd: &Path, file: &str) -> CargoResult<PathBu
     if fs::metadata(&manifest).is_ok() {
         Ok(manifest)
     } else {
-        Err(human(format!("Could not find `{}` in `{}`",
-                          file, pwd.display())))
+        Err(format!("Could not find `{}` in `{}`",
+                          file, pwd.display()).into())
     }
 }
index 14ec2419a41a3424fc6c983293b9911335dcd9ff..b1eda3cabeb90360d749b3471ac53b500a6b9f93 100644 (file)
@@ -3,7 +3,7 @@ pub use self::config::{Config, ConfigValue, homedir};
 pub use self::dependency_queue::{DependencyQueue, Fresh, Dirty, Freshness};
 pub use self::errors::{CargoResult, CargoResultExt, CargoError, CargoErrorKind, Test, CliResult};
 pub use self::errors::{CliError, ProcessError, CargoTestError};
-pub use self::errors::{process_error, internal_error, internal, human};
+pub use self::errors::{process_error, internal};
 pub use self::flock::{FileLock, Filesystem};
 pub use self::graph::Graph;
 pub use self::hex::{to_hex, short_hash, hash_u64};
index c8765e6eab092fe30d345d39cc3b41818781eaee..d41e1cd2e2291686f34c370c361f8896743bc7ee 100644 (file)
@@ -1,51 +1,28 @@
 use util::Config;
-use util::errors::CargoResult;
+use util::errors::{CargoError, CargoErrorKind, CargoResult};
 
-use curl;
 use git2;
 
-// =============================================================================
-// NetworkError chain
-error_chain!{
-    types {
-        NetworkError, NetworkErrorKind, NetworkResultExt, NetworkResult;
-    }
-
-    foreign_links {
-        Git(git2::Error);
-        Curl(curl::Error);
-    }
-
-    errors {
-        HttpNot200(code: u32, url: String) {
-            description("failed to get a 200 response")
-            display("failed to get 200 response from `{}`, got {}", url, code)
-        }
-    }
-}
-
-impl NetworkError {
-    pub fn maybe_spurious(&self) -> bool {
-        match &self.0 {
-            &NetworkErrorKind::Msg(_) => false,
-            &NetworkErrorKind::Git(ref git_err) => {
+fn maybe_spurious(err: &CargoError) -> bool {
+    match err.kind() {
+            &CargoErrorKind::Git(ref git_err) => {
                 match git_err.class() {
                     git2::ErrorClass::Net |
                     git2::ErrorClass::Os => true,
                     _ => false
                 }
             }
-            &NetworkErrorKind::Curl(ref curl_err) => {
+            &CargoErrorKind::Curl(ref curl_err) => {
                 curl_err.is_couldnt_connect() ||
                     curl_err.is_couldnt_resolve_proxy() ||
                     curl_err.is_couldnt_resolve_host() ||
                     curl_err.is_operation_timedout() ||
                     curl_err.is_recv_error()
             }
-            &NetworkErrorKind::HttpNot200(code, ref _url)  => {
+            &CargoErrorKind::HttpNot200(code, ref _url)  => {
                 500 <= code && code < 600
             }
-        }
+            _ => false
     }
 }
 
@@ -63,13 +40,13 @@ impl NetworkError {
 /// cargo_result = network.with_retry(&config, || something.download());
 /// ```
 pub fn with_retry<T, F>(config: &Config, mut callback: F) -> CargoResult<T>
-    where F: FnMut() -> NetworkResult<T>
+    where F: FnMut() -> CargoResult<T>
 {
     let mut remaining = config.net_retry()?;
     loop {
         match callback() {
             Ok(ret) => return Ok(ret),
-            Err(ref e) if e.maybe_spurious() && remaining > 0 => {
+            Err(ref e) if maybe_spurious(e) && remaining > 0 => {
                 let msg = format!("spurious network error ({} tries \
                           remaining): {}", remaining, e);
                 config.shell().warn(msg)?;
@@ -83,9 +60,9 @@ pub fn with_retry<T, F>(config: &Config, mut callback: F) -> CargoResult<T>
 #[test]
 fn with_retry_repeats_the_call_then_works() {
     //Error HTTP codes (5xx) are considered maybe_spurious and will prompt retry
-    let error1 = NetworkErrorKind::HttpNot200(501, "Uri".to_string()).into();
-    let error2 = NetworkErrorKind::HttpNot200(502, "Uri".to_string()).into();
-    let mut results: Vec<NetworkResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
+    let error1 = CargoErrorKind::HttpNot200(501, "Uri".to_string()).into();
+    let error2 = CargoErrorKind::HttpNot200(502, "Uri".to_string()).into();
+    let mut results: Vec<CargoResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
     let config = Config::default().unwrap();
     let result = with_retry(&config, || results.pop().unwrap());
     assert_eq!(result.unwrap(), ())
index d68d5d64b7de9cb5120b0ebd30500add5bdbd5e6..fecc166a555c2bf56b12dc39ecfab6547d323fc8 100644 (file)
@@ -5,16 +5,16 @@ use std::fs::OpenOptions;
 use std::io::prelude::*;
 use std::path::{Path, PathBuf, Component};
 
-use util::{human, internal, CargoResult};
+use util::{internal, CargoResult};
 use util::errors::CargoResultExt;
 
 pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
     env::join_paths(paths.iter()).or_else(|e| {
         let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
         Err(internal(format!("failed to join path array: {:?}", paths))).chain_err(|| {
-            human(format!("failed to join search paths together: {}\n\
+            format!("failed to join search paths together: {}\n\
                            Does ${} have an unterminated quote character?",
-                          e, env))
+                          e, env)
         })
     })
 }
@@ -74,8 +74,8 @@ pub fn read(path: &Path) -> CargoResult<String> {
         let mut f = File::open(path)?;
         f.read_to_string(&mut ret)?;
         Ok(ret)
-    })().map_err(human).chain_err(|| {
-        human(format!("failed to read `{}`", path.display()))
+    })().chain_err(|| {
+        format!("failed to read `{}`", path.display())
     })
 }
 
@@ -85,8 +85,8 @@ pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
         let mut f = File::open(path)?;
         f.read_to_end(&mut ret)?;
         Ok(ret)
-    })().map_err(human).chain_err(|| {
-        human(format!("failed to read `{}`", path.display()))
+    })().chain_err(|| {
+        format!("failed to read `{}`", path.display())
     })
 }
 
@@ -95,8 +95,8 @@ pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
         let mut f = File::create(path)?;
         f.write_all(contents)?;
         Ok(())
-    })().map_err(human).chain_err(|| {
-        human(format!("failed to write `{}`", path.display()))
+    })().chain_err(|| {
+        format!("failed to write `{}`", path.display())
     })
 }
 
@@ -124,8 +124,8 @@ pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
 pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
     match path.as_os_str().to_str() {
         Some(s) => Ok(s.as_bytes()),
-        None => Err(human(format!("invalid non-unicode path: {}",
-                                  path.display())))
+        None => Err(format!("invalid non-unicode path: {}",
+                            path.display()).into())
     }
 }
 
@@ -140,7 +140,7 @@ pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
     use std::str;
     match str::from_utf8(bytes) {
         Ok(s) => Ok(PathBuf::from(s)),
-        Err(..) => Err(human("invalid non-unicode path")),
+        Err(..) => Err("invalid non-unicode path".into()),
     }
 }
 
index c250937b3a291900f861be8b5119e70f85e0df73..5508bb9aadfac2afa330c4aeccef9764264b5131 100644 (file)
@@ -2,7 +2,7 @@ use std::path::Path;
 
 use url::Url;
 
-use util::{human, CargoResult};
+use util::CargoResult;
 
 pub trait ToUrl {
     fn to_url(self) -> CargoResult<Url>;
@@ -11,7 +11,7 @@ pub trait ToUrl {
 impl<'a> ToUrl for &'a str {
     fn to_url(self) -> CargoResult<Url> {
         Url::parse(self).map_err(|s| {
-            human(format!("invalid url `{}`: {}", self, s))
+            format!("invalid url `{}`: {}", self, s).into()
         })
     }
 }
@@ -19,7 +19,7 @@ impl<'a> ToUrl for &'a str {
 impl<'a> ToUrl for &'a Path {
     fn to_url(self) -> CargoResult<Url> {
         Url::from_file_path(self).map_err(|()| {
-            human(format!("invalid path url `{}`", self.display()))
+            format!("invalid path url `{}`", self.display()).into()
         })
     }
 }
index a9f8a5a8c96b9d5b14e8a7a2eafe9b0b920a5db2..d10eccdf16f747700e6164de4a028c9d63ab8588 100644 (file)
@@ -18,8 +18,8 @@ use core::dependency::{Kind, Platform};
 use core::manifest::{LibKind, Profile, ManifestMetadata};
 use ops::is_bad_artifact_name;
 use sources::CRATES_IO;
-use util::{self, CargoResult, human, ToUrl, ToSemver, Config};
-use util::errors::CargoResultExt;
+use util::{self, ToUrl, ToSemver, Config};
+use util::errors::{CargoError, CargoResult, CargoResultExt};
 
 /// Representation of the projects file layout.
 ///
@@ -191,7 +191,7 @@ in the future.", file.display());
     }
 
     Err(first_error).chain_err(|| {
-        human("could not parse input as TOML")
+        "could not parse input as TOML"
     })
 }
 
@@ -676,7 +676,7 @@ impl TomlManifest {
 
         let project = me.project.as_ref().or_else(|| me.package.as_ref());
         let project = project.ok_or_else(|| {
-            human("no `package` or `project` section found.")
+            CargoError::from("no `package` or `project` section found.")
         })?;
 
         if project.name.trim().is_empty() {
@@ -985,9 +985,9 @@ impl TomlManifest {
         let mut replace = Vec::new();
         for (spec, replacement) in self.replace.iter().flat_map(|x| x) {
             let mut spec = PackageIdSpec::parse(spec).chain_err(|| {
-                human(format!("replacements must specify a valid semver \
-                               version to replace, but `{}` does not",
-                              spec))
+                format!("replacements must specify a valid semver \
+                         version to replace, but `{}` does not",
+                        spec)
             })?;
             if spec.url().is_none() {
                 spec.set_url(CRATES_IO.parse().unwrap());
@@ -1004,11 +1004,10 @@ impl TomlManifest {
 
             let dep = replacement.to_dependency(spec.name(), cx, None)?;
             let dep = {
-                let version = spec.version().ok_or_else(||
-                {
-                    human(format!("replacements must specify a version \
-                                   to replace, but `{}` does not",
-                                  spec))
+                let version = spec.version().ok_or_else(|| {
+                    CargoError::from(format!("replacements must specify a version \
+                             to replace, but `{}` does not",
+                            spec))
                 })?;
                 let req = VersionReq::exact(version);
                 dep.clone_inner().set_version_req(req)
@@ -1249,10 +1248,10 @@ impl TomlTarget {
         match self.name {
             Some(ref name) => {
                 if name.trim().is_empty() {
-                    Err(human("library target names cannot be empty.".to_string()))
+                    Err("library target names cannot be empty.".into())
                 } else if name.contains('-') {
-                    Err(human(format!("library target names cannot contain hyphens: {}",
-                                      name)))
+                    Err(format!("library target names cannot contain hyphens: {}",
+                                 name).into())
                 } else {
                     Ok(())
                 }
@@ -1265,12 +1264,12 @@ impl TomlTarget {
         match self.name {
             Some(ref name) => {
                 if name.trim().is_empty() {
-                    Err(human("binary target names cannot be empty.".to_string()))
+                    Err("binary target names cannot be empty.".into())
                 } else {
                     Ok(())
                 }
             },
-            None => Err(human("binary target bin.name is required".to_string()))
+            None => Err("binary target bin.name is required".into())
         }
     }
 
@@ -1278,12 +1277,12 @@ impl TomlTarget {
         match self.name {
             Some(ref name) => {
                 if name.trim().is_empty() {
-                    Err(human("example target names cannot be empty".to_string()))
+                    Err("example target names cannot be empty".into())
                 } else {
                     Ok(())
                 }
             },
-            None => Err(human("example target example.name is required".to_string()))
+            None => Err("example target example.name is required".into())
         }
     }
 
@@ -1291,12 +1290,12 @@ impl TomlTarget {
         match self.name {
             Some(ref name) => {
                 if name.trim().is_empty() {
-                    Err(human("test target names cannot be empty".to_string()))
+                    Err("test target names cannot be empty".into())
                 } else {
                     Ok(())
                 }
             },
-            None => Err(human("test target test.name is required".to_string()))
+            None => Err("test target test.name is required".into())
         }
     }
 
@@ -1304,12 +1303,12 @@ impl TomlTarget {
         match self.name {
             Some(ref name) => {
                 if name.trim().is_empty() {
-                    Err(human("bench target names cannot be empty".to_string()))
+                    Err("bench target names cannot be empty".into())
                 } else {
                     Ok(())
                 }
             },
-            None => Err(human("bench target bench.name is required".to_string()))
+            None => Err("bench target bench.name is required".into())
         }
     }
 
@@ -1324,7 +1323,7 @@ impl TomlTarget {
         // A plugin requires exporting plugin_registrar so a crate cannot be
         // both at once.
         if self.plugin == Some(true) && self.proc_macro() == Some(true) {
-            Err(human("lib.plugin and lib.proc-macro cannot both be true".to_string()))
+            Err("lib.plugin and lib.proc-macro cannot both be true".into())
         } else {
             Ok(())
         }
index 4a292e6cb18f79e1d11d38284d233f096db6143c..119b5d32a44671bf45bfb60e1d44ca24ab3037c1 100644 (file)
@@ -365,9 +365,9 @@ fn output_not_captured() {
         let stderr = str::from_utf8(&output.stderr).unwrap();
     
         assert!(stderr.contains("☃"), "no snowman\n{}", stderr);
-        assert!(stderr.contains("unknown start of token"), "no message\n{}", stderr);
-    }else{
-        assert!(false, "an error kind other than ProcessErrorKind was encountered\n");
+        assert!(stderr.contains("unknown start of token"), "no message{}", stderr);
+    } else {
+        assert!(false, "an error kind other than ProcessErrorKind was encountered");
     }
 }